package com.example.dollarShipping.controller.auth;


import com.example.dollarShipping.entity.User;
import com.example.dollarShipping.service.UserService;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.util.Objects;

@Controller
@RequestMapping("/registration")
public class RegistrationController {

    @Resource
    private UserService userService;
    @Resource
    PasswordEncoder encoder;

    @ModelAttribute("user")
    public User userRegistrationDto() {
        return new User();
    }
//    @ModelAttribute("background")
//    public String backGround() {
//        return "../static/img/background2.png";
//    }

    @GetMapping
    public String showRegistrationForm() {
        System.out.println("show");
        return "auth/registration";
    }

    @PostMapping
    public String registerUserAccount(@ModelAttribute("user") @Valid User user,
                                      BindingResult result){

        if (user.getRoleId()==null){
            result.rejectValue("roleId", null, "Please select a registration role");
        }
        if (user.getConfirmPassword()!=null&&!Objects.equals(user.getPassword(), user.getConfirmPassword())){
            result.rejectValue("confirmPassword", null, "The two passwords do not match");
        }
        if (userService.existsByUsername(user.getUserName())) {
            result.rejectValue("userName", null, "There is already an account registered with that username");
        }
        if (userService.existsByEmail(user.getEmail())){
            result.rejectValue("email", null, "There is already an account registered with that email");
        }
        if (result.hasErrors()){
            return "auth/registration";
        }
		user.setPassword(encoder.encode(user.getPassword()));
        userService.save(user);
        return "redirect:registration?success";
    }

}
